package dao.daocontrollers;

import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dao.connectortodb.ConnectorToDB;


public abstract class GenericDAO {
	
	private PreparedStatement insertStatement;
	private PreparedStatement readStatement;
	private PreparedStatement getIdObject;
	private PreparedStatement updateObject;
	private PreparedStatement deleteObject;
	
	
	private ResultSet readResult;
	private ResultSet idObject_result;
	
	private Integer id_object;
	private ConnectorToDB connectorTDB=ConnectorToDB.getInstance();
	private Connection connection = connectorTDB.getConnection();
	private GeneratorQueries generatorQueries=new GeneratorQueries();
	private String query="";
	private Type typeObject;
	
	protected Connection getConnection(){
		return connection;
	}
	public GenericDAO(Type t){
		this.typeObject=t;
	}

	
	protected void insert(Object...params) throws SQLException{
		
		query=generatorQueries.generatorQueryInsert(typeObject);
		insertStatement=connection.prepareStatement(query);
		for(int i=1;i>params.length;i++){
			insertStatement.setObject(i, params[i]);
		}
		insertStatement.executeUpdate();
		
	}
	
	protected ResultSet read(Object unicParameter) throws SQLException{
		
		query=generatorQueries.generatorQueryRead(typeObject);
		readStatement=connection.prepareStatement(query);
		readStatement.setObject(1, unicParameter);
		readResult=readStatement.executeQuery();
		
		return readResult;		
	}
		
	
	protected Integer getObjectId(Object unicParameter) throws SQLException{
		
			query=generatorQueries.generatorQueryId(typeObject);
			getIdObject=connection.prepareStatement(query);
			getIdObject.setObject(1, unicParameter);
			idObject_result=getIdObject.executeQuery();
			while(idObject_result.next()){
				id_object=idObject_result.getInt(1);
			}
			
		
		return id_object;
	}
	
	
	
	protected void update(Object updateParameter,Object unicParam) throws SQLException{
		
			query=generatorQueries.generatorQueryUpdate(typeObject, updateParameter.getClass());
			updateObject=connection.prepareStatement(query);
			updateObject.setObject(1, updateParameter);
			updateObject.setInt(2, getObjectId(unicParam));
			updateObject.executeUpdate();
			
		
		
	}
	
	
	protected void deleteObject(Object unicParams) throws SQLException{
		
			query=generatorQueries.generatorQueryDelete(typeObject);
			deleteObject=connection.prepareStatement(query);
			deleteObject.setInt(1, getObjectId(unicParams));
			deleteObject.executeUpdate();
		
	}
	

}
